package main

import (
	"fmt"
	"dudu/util"
	"os"
	"bufio"
	"io"
	"strings"
)

func main() {
	fmt.Println("########开始执行....")

	curPath := util.GetCurrentDirectory();
	fmt.Println("当前目录:" + curPath)

	csvFiles, err := util.ListDir(curPath, ".csv")
	check(err)

	for _, csvPath := range csvFiles {
		if strings.Contains(csvPath, "_md5") {
			continue
		}

		fmt.Println("\r\n开始处理文件：" + csvPath)
		csvWritePath := csvPath[0:len(csvPath)-4] + "_md5.csv"

		if util.CheckFileIsExist(csvWritePath) {
			fmt.Println(csvWritePath + "文件已存在，不在生成")
			continue
		}

		wrFile(csvPath, csvWritePath)
		fmt.Println("生成文件：" + csvWritePath)
	}

	txtFiles, err := util.ListDir(curPath, ".txt")
	check(err)

	for _, txtPath := range txtFiles {
		if strings.Contains(txtPath, "_md5") {
			continue
		}

		fmt.Println("\r\n开始处理文件：" + txtPath)
		txtWritePath := txtPath[0:len(txtPath)-4] + "_md5.txt"

		if util.CheckFileIsExist(txtWritePath) {
			fmt.Println(txtWritePath + "文件已存在，不在生成")
			continue
		}

		wrFile(txtPath, txtWritePath)
		fmt.Println("生成文件：" + txtWritePath)
	}

	fmt.Println("\r\n########执行完成~！~\r\n")

	fmt.Println("输入回车退出......")
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		ucl := scanner.Text()
		fmt.Println(ucl)

		os.Exit(1)
	}
}

func wrFile(srcPath string, destPath string) {
	csvWriteFile, err := os.Create(destPath) //创建文件
	check(err)

	defer csvWriteFile.Close()

	wr := bufio.NewWriter(csvWriteFile)

	fi, err := os.Open(srcPath)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return
	}
	defer fi.Close()

	br := bufio.NewReader(fi)
	for {
		a, _, c := br.ReadLine()
		if c == io.EOF {
			break
		}

		tmpStr := string(a)
		if len(tmpStr) == 0 {
			continue
		}

		index := strings.Index(tmpStr, ",")
		if index == -1 {
			wr.WriteString(strings.ToUpper(util.Md5(tmpStr)) + "\r\n")
		} else {
			wr.WriteString(strings.ToUpper(util.Md5(tmpStr[0:index])) + tmpStr[index:] + "\r\n")
		}

		// fmt.Println(string(a))
	}

	wr.Flush()
}

func check(e error) {
	if e != nil {
		panic(e)
	}
}
